package jh.adapter

import android.content.Context
import android.os.Build
import android.support.v4.content.ContextCompat
import android.text.Html
import android.text.Spanned
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.jh.ios.forecast.R
import jh.interfaces.OnItemPictureClickListener
import jh.model.CModel
import jh.model.UserModel
import jh.utils.HttpUtils
import jh.view.NineGridTestLayout
import org.apache.cordova.FileManager
import org.jetbrains.anko.textColor
import java.util.HashMap

class PersonalCommunityAdapter(private val context: Context, private val datas: List<CModel>, private val listener: OnItemPictureClickListener) : BaseAdapter() {
    private val inflater: LayoutInflater
    private val hideIcon: Boolean? = null

    init {
        this.inflater = LayoutInflater.from(context)
    }


    override fun getCount(): Int {
        return datas.size
    }

    override fun getItem(position: Int): Any? {
        return null
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView

        var viewHolder: ViewHolder? = null
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.personal_layout_community_item, null)
            viewHolder = ViewHolder(convertView)
            convertView!!.tag = viewHolder
        } else {
            viewHolder = convertView.tag as ViewHolder
        }

        val model = datas[position]

        if (model.photo.isNullOrBlank()){  //头像url为空
        }else {
            Glide.with(context).load(model.photo).into(viewHolder.avatar)
        }
        viewHolder.name?.text = model.nickName
        if (position == 0) {  //如果是第一条  昵称黑色
            viewHolder.name?.setTextColor(ContextCompat.getColor(context, R.color.color222))
            viewHolder.img_one?.visibility=View.VISIBLE
            viewHolder.time?.visibility=View.VISIBLE
            viewHolder.title_one?.visibility=View.VISIBLE
            viewHolder.title?.visibility=View.GONE

            viewHolder.time?.text = model.createTime
            viewHolder.level?.text = model.gradeName  //会员等级
            if (model.mContent != null) {
                viewHolder.title_one?.text =setTextForHtml( model.mContent.toString())   //子评论页 显示组装的评论内容
            } else {
                viewHolder.title_one?.text = model.content
            }
        }else{
            viewHolder.img_one?.visibility=View.GONE
            viewHolder.time?.visibility=View.GONE
            viewHolder.title_one?.visibility=View.GONE
            viewHolder.title?.visibility=View.VISIBLE

            viewHolder.level?.text = model.createTime  //会员等级这里显示时间
            if (model.mContent != null) {
                viewHolder.title?.text =setTextForHtml( model.mContent.toString())   //子评论页 显示组装的评论内容
            } else {
                viewHolder.title?.text = model.content
            }
        }



        viewHolder.tag?.text = model.lotteryCategoryName

        //        viewHolder.content.setText(model.getContent());

        viewHolder.praise?.text = model.likeNumber.toString() + ""
        viewHolder.commentBtn?.setOnClickListener {
            lis?.let {
                it.onClick(model)
            }
        }
        viewHolder.praiseBtn?.setOnClickListener { praiseAction(model,position) }

        val path = FileManager.getFilePath() + "/www/assets/vip/"
        if (model.gradeCode - 1 > 0) {
            val vipImageName = path + "/vip" + (model.gradeCode - 1) + ".png"
            Glide.with(context).load(vipImageName).into(viewHolder.vip)
            viewHolder.vip?.visibility = View.VISIBLE
        } else {
            viewHolder.vip?.visibility = View.GONE
        }
        if (model.isDz == 1) {
            viewHolder.dz?.setImageDrawable(context.resources.getDrawable(R.mipmap.press))
        } else {
            viewHolder.dz?.setImageDrawable(context.resources.getDrawable(R.mipmap.press_norme))
        }

        if (model.imgs == null) {
            Log.e("ewfsdfsdfsdfs==", "null----")
            viewHolder.nineTestlayout?.visibility = View.GONE
        } else {
            Log.e("ewfsdfsdfsdfs==", "yes-----" + model.imgs)
            viewHolder.nineTestlayout?.visibility = View.VISIBLE

            viewHolder.nineTestlayout?.setListener(listener)

            viewHolder.nineTestlayout?.setItemPosition(position)
            viewHolder.nineTestlayout?.setIsShowAll(false) //当传入的图片数超过9张时，是否全部显示
            viewHolder.nineTestlayout?.setSpacing(5f) //动态设置图片之间的间隔
            viewHolder.nineTestlayout?.setUrlList(model.imgs!!.split(","))

        }
        if (model.ccId != -1) {   //子评论页才会有ccId字段
            viewHolder.comment?.text = "回复"
        } else {
            viewHolder.comment?.text = "${model.count}"  //点赞条数
        }
        return convertView
    }

    private fun praiseAction(model: CModel,posi:Int) {

        val userModel = UserModel.getUserInfo(context)
        val map = HashMap<String, String>()
        map.put("id", model.id.toString() + "")
        map.put("loginToken", userModel.loginToken)
        if (model.isDz == 1) {
            val url: String = if (posi==0){
                "/api/communicationcircle/qxDz"
            }else{
                "/api/communicationCircleDetail/qxDz"
            }

            HttpUtils.POST(url, map) { `object`, msg, e ->
                if (e == null) {
                    if (msg == null) {
                        model.likeNumber = model.likeNumber - 1
                        model.isDz = 0
                        notifyDataSetChanged()
                    }
                }
            }
        } else {
            val url: String = if (posi==0){
                "/api/communicationcircle/updateLike"
            }else{
                "/api/communicationCircleDetail/updateLike"
            }
            HttpUtils.POST(url, map) { `object`, msg, e ->
                if (e == null) {
                    if (msg == null) {
                        model.likeNumber = model.likeNumber + 1
                        model.isDz = 1
                        notifyDataSetChanged()
                    }
                }
            }
        }
    }


    inner class ViewHolder(view: View) {
        var avatar: ImageView? = null
        var vip: ImageView? = null
        var dz: ImageView? = null
        var name: TextView? = null
        var level: TextView? = null
        var tag: TextView? = null
        var title: TextView? = null
        var title_one: TextView? = null
        //        public TextView content;
        var time: TextView? = null
        var comment: TextView? = null
        var praise: TextView? = null
        var commentBtn: View? = null
        var praiseBtn: View? = null
        var img_one: ImageView? = null

        var nineTestlayout: NineGridTestLayout? = null

        init {
            avatar = view.findViewById(R.id.avatar)
            vip = view.findViewById(R.id.vip_icon)
            name = view.findViewById(R.id.name)
            level = view.findViewById(R.id.level)
            tag = view.findViewById(R.id.tag)
            title = view.findViewById(R.id.title)
            title_one = view.findViewById(R.id.title_one)
            //            content = view.findViewById(R.id.content);
            time = view.findViewById(R.id.time)
            comment = view.findViewById(R.id.comment)
            praise = view.findViewById(R.id.praise)
            praiseBtn = view.findViewById(R.id.praiseBtn)
            commentBtn = view.findViewById(R.id.commentBtn)
            dz = view.findViewById(R.id.dz)
            nineTestlayout = view.findViewById(R.id.nineTestlayout)
            img_one = view.findViewById(R.id.img_one)
        }

    }

//    var listner: ((itemBean: CModel) -> Unit)? = null
//
//    fun setMyListner(listner: (itemBean: CModel) -> Unit) {
//        this.listner = listner
//    }

    var lis: Listener<CModel>? = null

    interface Listener<CModel> {
        fun onClick(a: jh.model.CModel)
    }

    fun setaaListener(listener: Listener<CModel>) {
        this.lis = listener
    }

    /**
     * 设置html（解析html）
     *
     * @param html
     * @return
     */
    fun setTextForHtml(html: String): Spanned? {
        var result: Spanned? = null
        result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(html, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        } else {
            Html.fromHtml(html)
        }
        return result
    }
}